#include "sdlqtrgb.h"
#include <SDL.h>
#include <QMessageBox>
#pragma comment(lib, "SDL2.lib")
static SDL_Window *sdl_win = NULL;
static SDL_Renderer *sdl_render = NULL;
static SDL_Texture *sdl_texture = NULL;
static int sdl_width = 0;
static int sdl_height = 0;
static unsigned char *rgb = NULL;
static int pix_size = 4;
void SdlQtRGB::timerEvent(QTimerEvent *ev)
{
    SDL_UpdateTexture(sdl_texture, NULL, rgb, sdl_width * pix_size);
    SDL_RenderClear(sdl_render);
    SDL_Rect rect;
    rect.x = 0;
    rect.y = 0;
    rect.w = ui.label->width() * ui.label->devicePixelRatio();
    rect.h = ui.label->height() * ui.label->devicePixelRatio();
    SDL_RenderCopy(sdl_render, sdl_texture, NULL, &rect);
    SDL_RenderPresent(sdl_render);
}

SdlQtRGB::SdlQtRGB(QWidget *parent)
    : QWidget(parent)
{
    ui.setupUi(this);
    sdl_width = ui.label->width();
    sdl_height = ui.label->height();
    SDL_Init(SDL_INIT_VIDEO);
    sdl_win = SDL_CreateWindowFrom((void *)ui.label->winId());
    sdl_render = SDL_CreateRenderer(sdl_win, -1, SDL_RENDERER_ACCELERATED);
    auto s = qApp->applicationDirPath();
    QImage img1 = QImage(s + "/001.png");
    QImage img2 = QImage(s + "/002.png");
    if (img1.isNull() || img2.isNull())
    {
        qDebug() << "img1 or img2 is null";
        auto messageBox = QMessageBox(QMessageBox::Critical, "Error", "img1 or img2 is null");
        messageBox.exec();
        exit(1);
    }
    int out_width = img1.width() + img2.width();
    int out_height = img1.height();
    if (out_height < img2.height())
        out_height = img2.height();
    sdl_width = out_width;
    sdl_height = out_height;
    resize(sdl_width, sdl_height);
    ui.label->move(0, 0);
    ui.label->resize(sdl_width, sdl_height);
    sdl_texture = SDL_CreateTexture(sdl_render,
                                    SDL_PIXELFORMAT_ARGB8888,
                                    SDL_TEXTUREACCESS_STREAMING,
                                    sdl_width,
                                    sdl_height);
    rgb = new unsigned char[sdl_width * sdl_height * pix_size];
    memset(rgb, 0, sdl_width * sdl_height * pix_size);
    // ?????
    for (int i = 0; i < sdl_height; i++)
    {
        int b = i * sdl_width * pix_size;
        if (i < img1.height())
        {
            memcpy(rgb + b, img1.scanLine(i), img1.bytesPerLine());
        }
        b += img1.bytesPerLine();
        if (i < img2.height())
        {
            memcpy(rgb + b, img2.scanLine(i), img2.bytesPerLine());
        }
    }
    startTimer(10);
}